package itsense.model;

import java.util.List;

import itsense.client.BeautySenseGWT;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourcePasswordField;
import com.smartgwt.client.data.fields.DataSourceSequenceField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class MemberDS extends DataSource{
	private static MemberDS instance = null;  
	  
	public static MemberDS getInstance() {  
		if (instance == null)  instance = new MemberDS("memberDS");    
	    return instance;  
    }  
	
	public MemberDS(String id) {
		setID(id);
		DataSourceIntegerField idField = new DataSourceIntegerField("id","Id");
		idField.setPrimaryKey(true);
		DataSourceTextField firstName = new DataSourceTextField("firstName", "First name");  
		DataSourceTextField lastName = new DataSourceTextField("lastName", "Last name");  
		DataSourceTextField loginName = new DataSourceTextField("login", "Login");  
		DataSourcePasswordField passwordName = new DataSourcePasswordField("password", "Password");  
		DataSourceTextField emailName = new DataSourceTextField("email", "E-mail");
		setFields(idField,firstName,lastName,loginName,passwordName,emailName);
		setClientOnly(true);

	}
	
	@Override
	protected Object transformRequest(DSRequest dsRequest) {
		System.out.println("transformRequest = " + dsRequest);
		return super.transformRequest(dsRequest);
	}
	
	@Override
	protected void transformResponse(DSResponse response, DSRequest request, Object data) {
		System.out.println("transformtransformResponse = " + response + "  " + request);
		super.transformResponse(response, request, data);
	}
	
	
	public void getMembersFromServer(){
		
		BeautySenseGWT.service.getMembers(new AsyncCallback<List<MemberDTO>>() {
			public void onSuccess(List<MemberDTO> result) {
				System.out.print("Length = " + result.size());
				for (int i = 0 ; i < result.size() ;i++){
					ListGridRecord gridRec = new ListGridRecord();
					gridRec.setAttribute("password", result.get(i).getPassword());
					gridRec.setAttribute("id", result.get(i).getId());
					gridRec.setAttribute("email", result.get(i).getEmail());
					gridRec.setAttribute("firstName", result.get(i).getFirstName());
					gridRec.setAttribute("lastName", result.get(i).getLastName());
					gridRec.setAttribute("login", result.get(i).getLogin());
					addData(gridRec);

				}
				
			}
			
			public void onFailure(Throwable caught) {
				
			}
		});
	} 

	
}
